package org.springblade.modules.huikecloud.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.springblade.common.constant.CommonConstant;
import org.springblade.modules.system.entity.Param;
import org.springblade.modules.system.service.IParamService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

@Service
public class AsyncService {


    @Autowired
    public JavaMailSender mailSender;
    @Value("${spring.mail.username}")
    public String username;
    @Autowired
    private IParamService paramService;

    @Async  //标注这是一个异步执行的方法
    public void sendMail(String from, String to, String subject, String text) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from);
        message.setTo(to);
        message.setSubject(subject);
        message.setText(text);
        mailSender.send(message);
        System.out.println(from + "--->" + to + "   邮件发送成功");

    }

    @Async  //发送给管理员
    public void sendAdminMail(String subject, String text) {
        QueryWrapper<Param> paramQueryWrapper=new QueryWrapper<>();
        Param param = paramService.getOne(paramQueryWrapper.lambda().eq(Param::getParamKey, "cloud.email_to"));

        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(username);
        message.setTo(CommonConstant.CLOUD_EMAIL);
        if (param!=null&&StringUtils.checkValNotNull(param.getParamValue())){
            System.out.println("使用配置的管理员邮箱");
            message.setTo(param.getParamValue());
        }
        message.setSubject(subject);
        message.setText(text);
        mailSender.send(message);
        System.out.println(username + "--->" + CommonConstant.CLOUD_EMAIL + "   邮件发送成功");

    }
    @Async
    public void sendUserMail(String email_to,String subject, String text) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(username);
        message.setTo(email_to);
        message.setSubject(subject);
        message.setText(text);
        mailSender.send(message);
        System.out.println(username + "--->" + email_to + "   邮件发送成功");

    }


}
